<script setup>

import {useUserStore} from "@/stores/userStore";

const userStore = useUserStore();
import { getaddressAPI, delectAdressAPI, upDateAddressAPI, addAddressAPI,getReginAPI } from '@/apis/address'
// 获取用户信息
const userId = userStore.userInfo.userId


// 响应式数据
let index;//2修改  1添加

const reginAllList = ref([])
const addressList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加地址')
const isEdit = ref(false)//是否可以被编辑
const addressForm = ref({
  userId:userStore.userInfo.userId,
  addressId:undefined,
  recipientName: '222',
  recipientPhone: '232434',
  expressfeeId: null,
  recipientAddress: ''
});

// 表单校验规则
const rules = {
 recipientName: [
   { required: true, message: '请输入收货人姓名', trigger: 'blur' }
 ],
 recipientPhone: [
   { required: true, message: '请输入联系电话', trigger: 'blur' },
   { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
 ],
 expressfeeId: [
   { required: true, message: '请输入所在地区', trigger: 'blur' }
 ],
 recipientAddress: [
   { required: true, message: '请输入详细地址', trigger: 'blur' }
 ]
}
const addressFormRef = ref(null)
// 获取地址列表

const getAddressList = async () => {
 try {
  
   const res = await getaddressAPI(userId)
   addressList.value = res.data.list
   console.log( addressList.value);
 } catch (error) {
   ElMessage.error('获取地址列表失败')
 }
}
const getReginList = async () => {
 try {
  
   const res = await getReginAPI()
   reginAllList.value = res.data.list
 } catch (error) {
   ElMessage.error('获取地区列表失败')
 }
}
// 打开新增地址对话框
const handleCreate = () => {
  index=1;//添加
 isEdit.value = true
 dialogTitle.value = '添加地址'

 addressForm.value.userId = userStore.userInfo.userId;
 addressForm.value = {
    userId:userStore.userInfo.userId,
   addressId: 0,
   recipientName: '22',
   recipientPhone: '22',
   expressfeeId: 0,
   recipientRegion: '',
   recipientAddress: 'wrer'
 }
 dialogVisible.value = true
}

// 打开编辑地址对话框
const handleEdit = (item) => {
  console.log(item.recipientName)
 isEdit.value = true
 index=2;
 addressForm.value = {
    ...addressForm.value, // 保留 addressForm.value 的当前状态（这里假设它已经被正确初始化）
    userId: userStore.userInfo.userId, // 始终设置 userId
    addressId: item.addressId, // 更新 addressId
    // 以下属性将从 item 中复制，但仅当它们存在于 item 中时
    recipientName: item.recipientName || '',
    recipientPhone: item.recipientPhone || '',
    recipientRegion: item.recipientRegion || '',
    recipientAddress: item.recipientAddress || ''
    
  };
  console.log(addressForm.value.recipientName)
 dialogTitle.value = '编辑地址'
 dialogVisible.value = true

}
// 删除地址
const handleDelete = async (addressId) => {
  console.log(addressId)
 try {
   await ElMessageBox.confirm('确认删除该地址吗？', '提示', {
     type: 'warning'
   })
   await delectAdressAPI(addressId)
   ElMessage.success('删除成功')
   getAddressList()
 } catch (error) {
   if (error !== 'cancel') {
     ElMessage.error('删除失败')
   }
 }
}
// 提交表单
// 提交表单
const submitForm = async () => {
  try {
    // await addressFormRef.value.validate(); // 校验表单
    if (index === 2) {
      await upDateAddressAPI(addressForm.value);
      ElMessage.success('修改成功');
    } else if (index === 1) {
      await addAddressAPI(addressForm.value);
      ElMessage.success('添加成功');
    }
    getAddressList();
  } catch (error) {
    ElMessage.error(isEdit.value ? '修改失败' : '添加失败');
  }
};
// 页面加载时获取地址列表
onMounted(() => {
   Promise.all([getAddressList(), getReginList(),]) // 使用 Promise.all
       .then(([addressList, regionList]) => {
           // 处理 addressList 和 regionList
       })
       .catch(error => {
           console.error("获取地址或区域列表失败:", error);
       });
});
</script>
<template>
  <div class="address">
    <div class="address-header">
      <div class="address-header-title">收货地址</div>
     <div class="address-header-add" @click="handleCreate">添加地址</div>
   </div>
   
   <div class="address-list">
     <div class="address-list-item" v-for="item in addressList" :key="item.addressId">
       <div class="item-info">
         <div class="info-row">
           <span class="name">{{ item.recipientName }}</span>
           <span class="phone">{{ item.recipientPhone }}</span>
         </div>
         <div class="info-row">
           <span class="region">{{ item.recipientRegion }}</span>
           <span class="address">{{ item.recipientAddress }}</span>
         </div>
       </div>
       <div class="item-actions">
         <el-button type="text" @click="handleEdit(item)">编辑</el-button>
         <el-button type="text" @click="handleDelete(item.addressId)">删除</el-button>
       </div>
     </div>
   </div>
    <!-- 添加/编辑地址对话框 -->
   <el-dialog 
     :title="dialogTitle" 
     v-model="dialogVisible"
     width="500px"
   >
     <el-form 
      ref="addressFormRef"
       :model="addressForm"
       :rules="rules"
       label-width="80px"
     >
       <el-form-item label="姓名" prop="recipientName">
         <el-input v-model="addressForm.recipientName" placeholder="请输入收货人姓名"></el-input>
       </el-form-item>
       <el-form-item label="电话" prop="recipientPhone">
         <el-input v-model="addressForm.recipientPhone" placeholder="请输入联系电话"></el-input>
       </el-form-item>
       <el-form-item label="地区" prop="expressfeeId">
        <el-select v-model="addressForm.expressfeeId" placeholder="请选择地区" clearable class="filter-item" style="width: 130px; margin-left: 20px;">
          <el-option v-for="item in reginAllList" :key="item.expressfeeId" :label="item.regin+'('+item.expressfeeId+')'" :value="item.expressfeeId" />
        </el-select>
         <!-- <el-input v-model="addressForm.recipientRegion" placeholder="请输入所在地区"></el-input> -->
       </el-form-item>
       <el-form-item label="详细地址" prop="recipientAddress" class="address-item">
         <el-input 
           v-model="addressForm.recipientAddress" 
           type="textarea" 
           placeholder="请输入详细地址"
         ></el-input>
       </el-form-item>
     </el-form>
     <template #footer>
       <el-button @click="dialogVisible = false">取消</el-button>
       <el-button type="primary" @click="submitForm">确定</el-button>
     </template>
   </el-dialog>
 </div>
 
</template>
<style lang="scss" scoped>
/*address {
  padding: 20px;
 
  &-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
 
    &-title {
      font-size: 18px;
      font-weight: bold;
    }
 
    &-add {
      color: #409EFF;
      cursor: pointer;
    }
  }
 
  &-list {
    &-item {
      padding: 15px;
      border: 1px solid #EBEEF5;
      border-radius: 4px;
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      align-items: center;
 
      .item-info {
        .info-row {
          margin-bottom: 5px;
 
          &:last-child {
            margin-bottom: 0;
          }
 
          .name {
            margin-right: 20px;
            font-weight: bold;
          }
 
          .region {
            margin-right: 10px;
            color: #666;
          }
 
          .address {
            color: #666;
          }
        }
      }
 
      .item-actions {
        .el-button {
          padding: 0 10px;
        }
      }
    }
  }
}*/
.address {
    padding: 20px; /* 添加内边距 */    background-color: #f9f9f9; /* 背景颜色 */
   border-radius: 8px; /* 圆角边框 */
   box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 阴影效果 */
}
.address-header {
   display: flex; /* 使用弹性布局 */
   justify-content: space-between; /* 两端对齐 */
   align-items: center; /* 垂直居中 */
   margin-bottom: 15px; /* 底部间距 */
}
.address-header-title {
   font-size: 32px; /* 标题字体大小 */
   font-weight: bold; /* 加粗 */
}
.address-header-add {
   cursor: pointer; /* 鼠标悬停时显示为手型 */
   color: #409EFF; /* 添加地址的颜色 */
}
.address-list {
   border: 1px solid #e0e0e0; /* 列表边框 */
   border-radius: 4px; /* 圆角边框 */
   overflow: hidden; /* 隐藏溢出内容 */
}
.address-list-item {
   padding: 10px; /* 内边距 */
   border-bottom: 1px solid #e0e0e0; /* 分隔线 */
}
.address-list-item:last-child {
   border-bottom: none; /* 最后一个项不显示分隔线 */
}
.item-info {
  position: relative;
   margin-bottom: 5px; /* 信息项底部间距 */
}
.item-actions {
  font-size: 50px;
   display: flex; /* 使用弹性布局 */
   justify-content: flex-end; /* 右对齐 */
}
.el-dialog {
   border-radius: 8px; /* 对话框圆角 */
}
.el-form-item {
   margin-bottom: 15px; /* 表单项底部间距 */
}
.address{
  margin-left: 120px;
}
.info-row:first-child{
  margin-bottom: 20px;
}
.info-row .phone{
  margin-left: 20px;
}
</style>